{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "first_steps_with_tensor_flow.ipynb",
      "version": "0.3.2",
      "views": {},
      "default_view": {},
      "provenance": [],
      "collapsed_sections": [
        "ajVM7rkoYXeL",
        "ci1ISxxrZ7v0",
        "copyright-notice"
      ]
    }
  },
  "cells": [
    {
      "metadata": {
        "id": "copyright-notice",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "#### Copyright 2017 Google LLC."
      ]
    },
    {
      "metadata": {
        "cellView": "both",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        },
        "id": "copyright-notice2",
        "colab_type": "code"
      },
      "outputs": [],
      "execution_count": 0,
      "cell_type": "code",
      "source": [
        "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "metadata": {
        "id": "4f3CKqFUqL2-",
        "colab_type": "text",
        "slideshow": {
          "slide_type": "slide"
        }
      },
      "cell_type": "markdown",
      "source": [
        " # \u4f7f\u7528 TensorFlow \u7684\u57fa\u672c\u6b65\u9aa4"
      ]
    },
    {
      "metadata": {
        "id": "Bd2Zkk1LE2Zr",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        " **\u5b66\u4e60\u76ee\u6807\uff1a**\n",
        "  * \u5b66\u4e60\u57fa\u672c\u7684 TensorFlow \u6982\u5ff5\n",
        "  * \u5728 TensorFlow \u4e2d\u4f7f\u7528 `LinearRegressor` \u7c7b\u5e76\u57fa\u4e8e\u5355\u4e2a\u8f93\u5165\u7279\u5f81\u9884\u6d4b\u5404\u57ce\u5e02\u8857\u533a\u7684\u623f\u5c4b\u4ef7\u503c\u4e2d\u4f4d\u6570\n",
        "  * \u4f7f\u7528\u5747\u65b9\u6839\u8bef\u5dee (RMSE) \u8bc4\u4f30\u6a21\u578b\u9884\u6d4b\u7684\u51c6\u786e\u7387\n",
        "  * \u901a\u8fc7\u8c03\u6574\u6a21\u578b\u7684\u8d85\u53c2\u6570\u63d0\u9ad8\u6a21\u578b\u51c6\u786e\u7387"
      ]
    },
    {
      "metadata": {
        "id": "MxiIKhP4E2Zr",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        " \u6570\u636e\u57fa\u4e8e\u52a0\u5229\u798f\u5c3c\u4e9a\u5dde 1990 \u5e74\u7684\u4eba\u53e3\u666e\u67e5\u6570\u636e\u3002"
      ]
    },
    {
      "metadata": {
        "id": "6TjLjL9IU80G",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        " ## \u8bbe\u7f6e\n",
        "\u5728\u6b64\u7b2c\u4e00\u4e2a\u5355\u5143\u683c\u4e2d\uff0c\u6211\u4eec\u5c06\u52a0\u8f7d\u5fc5\u8981\u7684\u5e93\u3002"
      ]
    },
    {
      "metadata": {
        "id": "rVFf5asKE2Zt",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        }
      },
      "source": [
        "from __future__ import print_function\n",
        "\n",
        "import math\n",
        "\n",
        "from IPython import display\n",
        "from matplotlib import cm\n",
        "from matplotlib import gridspec\n",
        "from matplotlib import pyplot as plt\n",
        "import numpy as np\n",
        "import pandas as pd\n",
        "from sklearn import metrics\n",
        "import tensorflow as tf\n",
        "from tensorflow.python.data import Dataset\n",
        "\n",
        "tf.logging.set_verbosity(tf.logging.ERROR)\n",
        "pd.options.display.max_rows = 10\n",
        "pd.options.display.float_format = '{:.1f}'.format"
      ],
      "cell_type": "code",
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "ipRyUHjhU80Q",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        " \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u5c06\u52a0\u8f7d\u6570\u636e\u96c6\u3002"
      ]
    },
    {
      "metadata": {
        "id": "9ivCDWnwE2Zx",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        }
      },
      "source": [
        "california_housing_dataframe = pd.read_csv(\"https://download.mlcc.google.cn/mledu-datasets/california_housing_train.csv\", sep=\",\")"
      ],
      "cell_type": "code",
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "vVk_qlG6U80j",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        " \u6211\u4eec\u5c06\u5bf9\u6570\u636e\u8fdb\u884c\u968f\u673a\u5316\u5904\u7406\uff0c\u4ee5\u786e\u4fdd\u4e0d\u4f1a\u51fa\u73b0\u4efb\u4f55\u75c5\u6001\u6392\u5e8f\u7ed3\u679c\uff08\u53ef\u80fd\u4f1a\u635f\u5bb3\u968f\u673a\u68af\u5ea6\u4e0b\u964d\u6cd5\u7684\u6548\u679c\uff09\u3002\u6b64\u5916\uff0c\u6211\u4eec\u4f1a\u5c06 `median_house_value` \u8c03\u6574\u4e3a\u4ee5\u5343\u4e3a\u5355\u4f4d\uff0c\u8fd9\u6837\uff0c\u6a21\u578b\u5c31\u80fd\u591f\u4ee5\u5e38\u7528\u8303\u56f4\u5185\u7684\u5b66\u4e60\u901f\u7387\u8f83\u4e3a\u8f7b\u677e\u5730\u5b66\u4e60\u8fd9\u4e9b\u6570\u636e\u3002"
      ]
    },
    {
      "metadata": {
        "id": "r0eVyguIU80m",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        }
      },
      "source": [
        "california_housing_dataframe = california_housing_dataframe.reindex(\n",
        "    np.random.permutation(california_housing_dataframe.index))\n",
        "california_housing_dataframe[\"median_house_value\"] /= 1000.0\n",
        "california_housing_dataframe"
      ],
      "cell_type": "code",
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "HzzlSs3PtTmt",
        "colab_type": "text",
        "slideshow": {
          "slide_type": "-"
        }
      },
      "cell_type": "markdown",
      "source": [
        " ## \u68c0\u67e5\u6570\u636e\n",
        "\n",
        "\u5efa\u8bae\u60a8\u5728\u4f7f\u7528\u6570\u636e\u4e4b\u524d\uff0c\u5148\u5bf9\u5b83\u6709\u4e00\u4e2a\u521d\u6b65\u7684\u4e86\u89e3\u3002\n",
        "\n",
        "\u6211\u4eec\u4f1a\u8f93\u51fa\u5173\u4e8e\u5404\u5217\u7684\u4e00\u4e9b\u5b9e\u7528\u7edf\u8ba1\u4fe1\u606f\u5feb\u901f\u6458\u8981\uff1a\u6837\u672c\u6570\u3001\u5747\u503c\u3001\u6807\u51c6\u504f\u5dee\u3001\u6700\u5927\u503c\u3001\u6700\u5c0f\u503c\u548c\u5404\u79cd\u5206\u4f4d\u6570\u3002"
      ]
    },
    {
      "metadata": {
        "id": "gzb10yoVrydW",
        "colab_type": "code",
        "slideshow": {
          "slide_type": "slide"
        },
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          },
          "test": {
            "output": "ignore",
            "timeout": 600
          }
        },
        "cellView": "both"
      },
      "source": [
        "california_housing_dataframe.describe()"
      ],
      "cell_type": "code",
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "Lr6wYl2bt2Ep",
        "colab_type": "text",
        "slideshow": {
          "slide_type": "-"
        }
      },
      "cell_type": "markdown",
      "source": [
        " ## \u6784\u5efa\u7b2c\u4e00\u4e2a\u6a21\u578b\n",
        "\n",
        "\u5728\u672c\u7ec3\u4e60\u4e2d\uff0c\u6211\u4eec\u5c06\u5c1d\u8bd5\u9884\u6d4b `median_house_value`\uff0c\u5b83\u5c06\u662f\u6211\u4eec\u7684\u6807\u7b7e\uff08\u6709\u65f6\u4e5f\u79f0\u4e3a\u76ee\u6807\uff09\u3002\u6211\u4eec\u5c06\u4f7f\u7528 `total_rooms` \u4f5c\u4e3a\u8f93\u5165\u7279\u5f81\u3002\n",
        "\n",
        "**\u6ce8\u610f**\uff1a\u6211\u4eec\u4f7f\u7528\u7684\u662f\u57ce\u5e02\u8857\u533a\u7ea7\u522b\u7684\u6570\u636e\uff0c\u56e0\u6b64\u8be5\u7279\u5f81\u8868\u793a\u76f8\u5e94\u8857\u533a\u7684\u623f\u95f4\u603b\u6570\u3002\n",
        "\n",
        "\u4e3a\u4e86\u8bad\u7ec3\u6a21\u578b\uff0c\u6211\u4eec\u5c06\u4f7f\u7528 TensorFlow [Estimator](https://www.tensorflow.org/get_started/estimator) API \u63d0\u4f9b\u7684 [LinearRegressor](https://www.tensorflow.org/api_docs/python/tf/estimator/LinearRegressor) \u63a5\u53e3\u3002\u6b64 API \u8d1f\u8d23\u5904\u7406\u5927\u91cf\u4f4e\u7ea7\u522b\u6a21\u578b\u642d\u5efa\u5de5\u4f5c\uff0c\u5e76\u4f1a\u63d0\u4f9b\u6267\u884c\u6a21\u578b\u8bad\u7ec3\u3001\u8bc4\u4f30\u548c\u63a8\u7406\u7684\u4fbf\u5229\u65b9\u6cd5\u3002"
      ]
    },
    {
      "metadata": {
        "id": "0cpcsieFhsNI",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        " ### \u7b2c 1 \u6b65\uff1a\u5b9a\u4e49\u7279\u5f81\u5e76\u914d\u7f6e\u7279\u5f81\u5217"
      ]
    },
    {
      "metadata": {
        "id": "EL8-9d4ZJNR7",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        " \u4e3a\u4e86\u5c06\u6211\u4eec\u7684\u8bad\u7ec3\u6570\u636e\u5bfc\u5165 TensorFlow\uff0c\u6211\u4eec\u9700\u8981\u6307\u5b9a\u6bcf\u4e2a\u7279\u5f81\u5305\u542b\u7684\u6570\u636e\u7c7b\u578b\u3002\u5728\u672c\u7ec3\u4e60\u53ca\u4eca\u540e\u7684\u7ec3\u4e60\u4e2d\uff0c\u6211\u4eec\u4e3b\u8981\u4f1a\u4f7f\u7528\u4ee5\u4e0b\u4e24\u7c7b\u6570\u636e\uff1a\n",
        "\n",
        "* **\u5206\u7c7b\u6570\u636e**\uff1a\u4e00\u79cd\u6587\u5b57\u6570\u636e\u3002\u5728\u672c\u7ec3\u4e60\u4e2d\uff0c\u6211\u4eec\u7684\u4f4f\u623f\u6570\u636e\u96c6\u4e0d\u5305\u542b\u4efb\u4f55\u5206\u7c7b\u7279\u5f81\uff0c\u4f46\u60a8\u53ef\u80fd\u4f1a\u770b\u5230\u7684\u793a\u4f8b\u5305\u62ec\u5bb6\u5c45\u98ce\u683c\u4ee5\u53ca\u623f\u5730\u4ea7\u5e7f\u544a\u8bcd\u3002\n",
        "\n",
        "* **\u6570\u503c\u6570\u636e**\uff1a\u4e00\u79cd\u6570\u5b57\uff08\u6574\u6570\u6216\u6d6e\u70b9\u6570\uff09\u6570\u636e\u4ee5\u53ca\u60a8\u5e0c\u671b\u89c6\u4e3a\u6570\u5b57\u7684\u6570\u636e\u3002\u6709\u65f6\u60a8\u53ef\u80fd\u4f1a\u5e0c\u671b\u5c06\u6570\u503c\u6570\u636e\uff08\u4f8b\u5982\u90ae\u653f\u7f16\u7801\uff09\u89c6\u4e3a\u5206\u7c7b\u6570\u636e\uff08\u6211\u4eec\u5c06\u5728\u7a0d\u540e\u7684\u90e8\u5206\u5bf9\u6b64\u8fdb\u884c\u8be6\u7ec6\u8bf4\u660e\uff09\u3002\n",
        "\n",
        "\u5728 TensorFlow \u4e2d\uff0c\u6211\u4eec\u4f7f\u7528\u4e00\u79cd\u79f0\u4e3a\u201c**\u7279\u5f81\u5217**\u201d\u7684\u7ed3\u6784\u6765\u8868\u793a\u7279\u5f81\u7684\u6570\u636e\u7c7b\u578b\u3002\u7279\u5f81\u5217\u4ec5\u5b58\u50a8\u5bf9\u7279\u5f81\u6570\u636e\u7684\u63cf\u8ff0\uff1b\u4e0d\u5305\u542b\u7279\u5f81\u6570\u636e\u672c\u8eab\u3002\n",
        "\n",
        "\u4e00\u5f00\u59cb\uff0c\u6211\u4eec\u53ea\u4f7f\u7528\u4e00\u4e2a\u6570\u503c\u8f93\u5165\u7279\u5f81 `total_rooms`\u3002\u4ee5\u4e0b\u4ee3\u7801\u4f1a\u4ece `california_housing_dataframe` \u4e2d\u63d0\u53d6 `total_rooms` \u6570\u636e\uff0c\u5e76\u4f7f\u7528 `numeric_column` \u5b9a\u4e49\u7279\u5f81\u5217\uff0c\u8fd9\u6837\u4f1a\u5c06\u5176\u6570\u636e\u6307\u5b9a\u4e3a\u6570\u503c\uff1a"
      ]
    },
    {
      "metadata": {
        "id": "rhEbFCZ86cDZ",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        }
      },
      "source": [
        "# Define the input feature: total_rooms.\n",
        "my_feature = california_housing_dataframe[[\"total_rooms\"]]\n",
        "\n",
        "# Configure a numeric feature column for total_rooms.\n",
        "feature_columns = [tf.feature_column.numeric_column(\"total_rooms\")]"
      ],
      "cell_type": "code",
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "K_3S8teX7Rd2",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        " **\u6ce8\u610f**\uff1a`total_rooms` \u6570\u636e\u7684\u5f62\u72b6\u662f\u4e00\u7ef4\u6570\u7ec4\uff08\u6bcf\u4e2a\u8857\u533a\u7684\u623f\u95f4\u603b\u6570\u5217\u8868\uff09\u3002\u8fd9\u662f `numeric_column` \u7684\u9ed8\u8ba4\u5f62\u72b6\uff0c\u56e0\u6b64\u6211\u4eec\u4e0d\u5fc5\u5c06\u5176\u4f5c\u4e3a\u53c2\u6570\u4f20\u9012\u3002"
      ]
    },
    {
      "metadata": {
        "id": "UMl3qrU5MGV6",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        " ### \u7b2c 2 \u6b65\uff1a\u5b9a\u4e49\u76ee\u6807"
      ]
    },
    {
      "metadata": {
        "id": "cw4nrfcB7kyk",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        " \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u5c06\u5b9a\u4e49\u76ee\u6807\uff0c\u4e5f\u5c31\u662f `median_house_value`\u3002\u540c\u6837\uff0c\u6211\u4eec\u53ef\u4ee5\u4ece `california_housing_dataframe` \u4e2d\u63d0\u53d6\u5b83\uff1a"
      ]
    },
    {
      "metadata": {
        "id": "l1NvvNkH8Kbt",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        }
      },
      "source": [
        "# Define the label.\n",
        "targets = california_housing_dataframe[\"median_house_value\"]"
      ],
      "cell_type": "code",
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "4M-rTFHL2UkA",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        " ### \u7b2c 3 \u6b65\uff1a\u914d\u7f6e LinearRegressor"
      ]
    },
    {
      "metadata": {
        "id": "fUfGQUNp7jdL",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        " \u63a5\u4e0b\u6765\uff0c\u6211\u4eec\u5c06\u4f7f\u7528 LinearRegressor \u914d\u7f6e\u7ebf\u6027\u56de\u5f52\u6a21\u578b\uff0c\u5e76\u4f7f\u7528 `GradientDescentOptimizer`\uff08\u5b83\u4f1a\u5b9e\u73b0\u5c0f\u6279\u91cf\u968f\u673a\u68af\u5ea6\u4e0b\u964d\u6cd5 (SGD)\uff09\u8bad\u7ec3\u8be5\u6a21\u578b\u3002`learning_rate` \u53c2\u6570\u53ef\u63a7\u5236\u68af\u5ea6\u6b65\u957f\u7684\u5927\u5c0f\u3002\n",
        "\n",
        "**\u6ce8\u610f**\uff1a\u4e3a\u4e86\u5b89\u5168\u8d77\u89c1\uff0c\u6211\u4eec\u8fd8\u4f1a\u901a\u8fc7 `clip_gradients_by_norm` \u5c06[\u68af\u5ea6\u88c1\u526a](https://developers.google.com/machine-learning/glossary/#gradient_clipping)\u5e94\u7528\u5230\u6211\u4eec\u7684\u4f18\u5316\u5668\u3002\u68af\u5ea6\u88c1\u526a\u53ef\u786e\u4fdd\u68af\u5ea6\u5927\u5c0f\u5728\u8bad\u7ec3\u671f\u95f4\u4e0d\u4f1a\u53d8\u5f97\u8fc7\u5927\uff0c\u68af\u5ea6\u8fc7\u5927\u4f1a\u5bfc\u81f4\u68af\u5ea6\u4e0b\u964d\u6cd5\u5931\u8d25\u3002"
      ]
    },
    {
      "metadata": {
        "id": "ubhtW-NGU802",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        }
      },
      "source": [
        "# Use gradient descent as the optimizer for training the model.\n",
        "my_optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.0000001)\n",
        "my_optimizer = tf.contrib.estimator.clip_gradients_by_norm(my_optimizer, 5.0)\n",
        "\n",
        "# Configure the linear regression model with our feature columns and optimizer.\n",
        "# Set a learning rate of 0.0000001 for Gradient Descent.\n",
        "linear_regressor = tf.estimator.LinearRegressor(\n",
        "    feature_columns=feature_columns,\n",
        "    optimizer=my_optimizer\n",
        ")"
      ],
      "cell_type": "code",
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "-0IztwdK2f3F",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        " ### \u7b2c 4 \u6b65\uff1a\u5b9a\u4e49\u8f93\u5165\u51fd\u6570"
      ]
    },
    {
      "metadata": {
        "id": "S5M5j6xSCHxx",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        " \u8981\u5c06\u52a0\u5229\u798f\u5c3c\u4e9a\u5dde\u4f4f\u623f\u6570\u636e\u5bfc\u5165 `LinearRegressor`\uff0c\u6211\u4eec\u9700\u8981\u5b9a\u4e49\u4e00\u4e2a\u8f93\u5165\u51fd\u6570\uff0c\u8ba9\u5b83\u544a\u8bc9 TensorFlow \u5982\u4f55\u5bf9\u6570\u636e\u8fdb\u884c\u9884\u5904\u7406\uff0c\u4ee5\u53ca\u5728\u6a21\u578b\u8bad\u7ec3\u671f\u95f4\u5982\u4f55\u6279\u5904\u7406\u3001\u968f\u673a\u5904\u7406\u548c\u91cd\u590d\u6570\u636e\u3002\n",
        "\n",
        "\u9996\u5148\uff0c\u6211\u4eec\u5c06 *Pandas* \u7279\u5f81\u6570\u636e\u8f6c\u6362\u6210 NumPy \u6570\u7ec4\u5b57\u5178\u3002\u7136\u540e\uff0c\u6211\u4eec\u53ef\u4ee5\u4f7f\u7528 TensorFlow [Dataset API](https://www.tensorflow.org/programmers_guide/datasets) \u6839\u636e\u6211\u4eec\u7684\u6570\u636e\u6784\u5efa Dataset \u5bf9\u8c61\uff0c\u5e76\u5c06\u6570\u636e\u62c6\u5206\u6210\u5927\u5c0f\u4e3a `batch_size` \u7684\u591a\u6279\u6570\u636e\uff0c\u4ee5\u6309\u7167\u6307\u5b9a\u5468\u671f\u6570 (num_epochs) \u8fdb\u884c\u91cd\u590d\u3002\n",
        "\n",
        "**\u6ce8\u610f**\uff1a\u5982\u679c\u5c06\u9ed8\u8ba4\u503c `num_epochs=None` \u4f20\u9012\u5230 `repeat()`\uff0c\u8f93\u5165\u6570\u636e\u4f1a\u65e0\u9650\u671f\u91cd\u590d\u3002\n",
        "\n",
        "\u7136\u540e\uff0c\u5982\u679c `shuffle` \u8bbe\u7f6e\u4e3a `True`\uff0c\u5219\u6211\u4eec\u4f1a\u5bf9\u6570\u636e\u8fdb\u884c\u968f\u673a\u5904\u7406\uff0c\u4ee5\u4fbf\u6570\u636e\u5728\u8bad\u7ec3\u671f\u95f4\u4ee5\u968f\u673a\u65b9\u5f0f\u4f20\u9012\u5230\u6a21\u578b\u3002`buffer_size` \u53c2\u6570\u4f1a\u6307\u5b9a `shuffle` \u5c06\u4ece\u4e2d\u968f\u673a\u62bd\u6837\u7684\u6570\u636e\u96c6\u7684\u5927\u5c0f\u3002\n",
        "\n",
        "\u6700\u540e\uff0c\u8f93\u5165\u51fd\u6570\u4f1a\u4e3a\u8be5\u6570\u636e\u96c6\u6784\u5efa\u4e00\u4e2a\u8fed\u4ee3\u5668\uff0c\u5e76\u5411 LinearRegressor \u8fd4\u56de\u4e0b\u4e00\u6279\u6570\u636e\u3002"
      ]
    },
    {
      "metadata": {
        "id": "RKZ9zNcHJtwc",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        }
      },
      "source": [
        "def my_input_fn(features, targets, batch_size=1, shuffle=True, num_epochs=None):\n",
        "    \"\"\"Trains a linear regression model of one feature.\n",
        "  \n",
        "    Args:\n",
        "      features: pandas DataFrame of features\n",
        "      targets: pandas DataFrame of targets\n",
        "      batch_size: Size of batches to be passed to the model\n",
        "      shuffle: True or False. Whether to shuffle the data.\n",
        "      num_epochs: Number of epochs for which data should be repeated. None = repeat indefinitely\n",
        "    Returns:\n",
        "      Tuple of (features, labels) for next data batch\n",
        "    \"\"\"\n",
        "  \n",
        "    # Convert pandas data into a dict of np arrays.\n",
        "    features = {key:np.array(value) for key,value in dict(features).items()}                                           \n",
        " \n",
        "    # Construct a dataset, and configure batching/repeating.\n",
        "    ds = Dataset.from_tensor_slices((features,targets)) # warning: 2GB limit\n",
        "    ds = ds.batch(batch_size).repeat(num_epochs)\n",
        "    \n",
        "    # Shuffle the data, if specified.\n",
        "    if shuffle:\n",
        "      ds = ds.shuffle(buffer_size=10000)\n",
        "    \n",
        "    # Return the next batch of data.\n",
        "    features, labels = ds.make_one_shot_iterator().get_next()\n",
        "    return features, labels"
      ],
      "cell_type": "code",
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "wwa6UeA1V5F_",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        " **\u6ce8\u610f**\uff1a\u5728\u540e\u9762\u7684\u7ec3\u4e60\u4e2d\uff0c\u6211\u4eec\u4f1a\u7ee7\u7eed\u4f7f\u7528\u6b64\u8f93\u5165\u51fd\u6570\u3002\u6709\u5173\u8f93\u5165\u51fd\u6570\u548c `Dataset` API \u7684\u66f4\u8be6\u7ec6\u7684\u6587\u6863\uff0c\u8bf7\u53c2\u9605 [TensorFlow \u7f16\u7a0b\u4eba\u5458\u6307\u5357](https://www.tensorflow.org/programmers_guide/datasets)\u3002"
      ]
    },
    {
      "metadata": {
        "id": "4YS50CQb2ooO",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        " ### \u7b2c 5 \u6b65\uff1a\u8bad\u7ec3\u6a21\u578b"
      ]
    },
    {
      "metadata": {
        "id": "yP92XkzhU803",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        " \u73b0\u5728\uff0c\u6211\u4eec\u53ef\u4ee5\u5728 `linear_regressor` \u4e0a\u8c03\u7528 `train()` \u6765\u8bad\u7ec3\u6a21\u578b\u3002\u6211\u4eec\u4f1a\u5c06 `my_input_fn` \u5c01\u88c5\u5728 `lambda` \u4e2d\uff0c\u4ee5\u4fbf\u53ef\u4ee5\u5c06 `my_feature` \u548c `target` \u4f5c\u4e3a\u53c2\u6570\u4f20\u5165\uff08\u6709\u5173\u8be6\u60c5\uff0c\u8bf7\u53c2\u9605\u6b64 [TensorFlow \u8f93\u5165\u51fd\u6570\u6559\u7a0b](https://www.tensorflow.org/get_started/input_fn#passing_input_fn_data_to_your_model)\uff09\uff0c\u9996\u5148\uff0c\u6211\u4eec\u4f1a\u8bad\u7ec3 100 \u6b65\u3002"
      ]
    },
    {
      "metadata": {
        "id": "5M-Kt6w8U803",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        }
      },
      "source": [
        "_ = linear_regressor.train(\n",
        "    input_fn = lambda:my_input_fn(my_feature, targets),\n",
        "    steps=100\n",
        ")"
      ],
      "cell_type": "code",
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "7Nwxqxlx2sOv",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        " ### \u7b2c 6 \u6b65\uff1a\u8bc4\u4f30\u6a21\u578b"
      ]
    },
    {
      "metadata": {
        "id": "KoDaF2dlJQG5",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        " \u6211\u4eec\u57fa\u4e8e\u8be5\u8bad\u7ec3\u6570\u636e\u505a\u4e00\u6b21\u9884\u6d4b\uff0c\u770b\u770b\u6211\u4eec\u7684\u6a21\u578b\u5728\u8bad\u7ec3\u671f\u95f4\u4e0e\u8fd9\u4e9b\u6570\u636e\u7684\u62df\u5408\u60c5\u51b5\u3002\n",
        "\n",
        "**\u6ce8\u610f**\uff1a\u8bad\u7ec3\u8bef\u5dee\u53ef\u4ee5\u8861\u91cf\u60a8\u7684\u6a21\u578b\u4e0e\u8bad\u7ec3\u6570\u636e\u7684\u62df\u5408\u60c5\u51b5\uff0c\u4f46\u5e76**_\u4e0d\u80fd_**\u8861\u91cf\u6a21\u578b**_\u6cdb\u5316\u5230\u65b0\u6570\u636e_**\u7684\u6548\u679c\u3002\u5728\u540e\u9762\u7684\u7ec3\u4e60\u4e2d\uff0c\u60a8\u5c06\u63a2\u7d22\u5982\u4f55\u62c6\u5206\u6570\u636e\u4ee5\u8bc4\u4f30\u6a21\u578b\u7684\u6cdb\u5316\u80fd\u529b\u3002\n",
        ""
      ]
    },
    {
      "metadata": {
        "id": "pDIxp6vcU809",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        }
      },
      "source": [
        "# Create an input function for predictions.\n",
        "# Note: Since we're making just one prediction for each example, we don't \n",
        "# need to repeat or shuffle the data here.\n",
        "prediction_input_fn =lambda: my_input_fn(my_feature, targets, num_epochs=1, shuffle=False)\n",
        "\n",
        "# Call predict() on the linear_regressor to make predictions.\n",
        "predictions = linear_regressor.predict(input_fn=prediction_input_fn)\n",
        "\n",
        "# Format predictions as a NumPy array, so we can calculate error metrics.\n",
        "predictions = np.array([item['predictions'][0] for item in predictions])\n",
        "\n",
        "# Print Mean Squared Error and Root Mean Squared Error.\n",
        "mean_squared_error = metrics.mean_squared_error(predictions, targets)\n",
        "root_mean_squared_error = math.sqrt(mean_squared_error)\n",
        "print(\"Mean Squared Error (on training data): %0.3f\" % mean_squared_error)\n",
        "print(\"Root Mean Squared Error (on training data): %0.3f\" % root_mean_squared_error)"
      ],
      "cell_type": "code",
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "AKWstXXPzOVz",
        "colab_type": "text",
        "slideshow": {
          "slide_type": "slide"
        }
      },
      "cell_type": "markdown",
      "source": [
        " \u8fd9\u662f\u51fa\u8272\u7684\u6a21\u578b\u5417\uff1f\u60a8\u5982\u4f55\u5224\u65ad\u8bef\u5dee\u6709\u591a\u5927\uff1f\n",
        "\n",
        "\u7531\u4e8e\u5747\u65b9\u8bef\u5dee (MSE) \u5f88\u96be\u89e3\u8bfb\uff0c\u56e0\u6b64\u6211\u4eec\u7ecf\u5e38\u67e5\u770b\u7684\u662f\u5747\u65b9\u6839\u8bef\u5dee (RMSE)\u3002RMSE \u7684\u4e00\u4e2a\u5f88\u597d\u7684\u7279\u6027\u662f\uff0c\u5b83\u53ef\u4ee5\u5728\u4e0e\u539f\u76ee\u6807\u76f8\u540c\u7684\u89c4\u6a21\u4e0b\u89e3\u8bfb\u3002\n",
        "\n",
        "\u6211\u4eec\u6765\u6bd4\u8f83\u4e00\u4e0b RMSE \u4e0e\u76ee\u6807\u6700\u5927\u503c\u548c\u6700\u5c0f\u503c\u7684\u5dee\u503c\uff1a"
      ]
    },
    {
      "metadata": {
        "id": "7UwqGbbxP53O",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        }
      },
      "source": [
        "min_house_value = california_housing_dataframe[\"median_house_value\"].min()\n",
        "max_house_value = california_housing_dataframe[\"median_house_value\"].max()\n",
        "min_max_difference = max_house_value - min_house_value\n",
        "\n",
        "print(\"Min. Median House Value: %0.3f\" % min_house_value)\n",
        "print(\"Max. Median House Value: %0.3f\" % max_house_value)\n",
        "print(\"Difference between Min. and Max.: %0.3f\" % min_max_difference)\n",
        "print(\"Root Mean Squared Error: %0.3f\" % root_mean_squared_error)"
      ],
      "cell_type": "code",
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "JigJr0C7Pzit",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        " \u6211\u4eec\u7684\u8bef\u5dee\u8de8\u8d8a\u76ee\u6807\u503c\u7684\u8fd1\u4e00\u534a\u8303\u56f4\uff0c\u53ef\u4ee5\u8fdb\u4e00\u6b65\u7f29\u5c0f\u8bef\u5dee\u5417\uff1f\n",
        "\n",
        "\u8fd9\u662f\u6bcf\u4e2a\u6a21\u578b\u5f00\u53d1\u8005\u90fd\u4f1a\u70e6\u607c\u7684\u95ee\u9898\u3002\u6211\u4eec\u6765\u5236\u5b9a\u4e00\u4e9b\u57fa\u672c\u7b56\u7565\uff0c\u4ee5\u964d\u4f4e\u6a21\u578b\u8bef\u5dee\u3002\n",
        "\n",
        "\u9996\u5148\uff0c\u6211\u4eec\u53ef\u4ee5\u4e86\u89e3\u4e00\u4e0b\u6839\u636e\u603b\u4f53\u6458\u8981\u7edf\u8ba1\u4fe1\u606f\uff0c\u9884\u6d4b\u548c\u76ee\u6807\u7684\u7b26\u5408\u60c5\u51b5\u3002"
      ]
    },
    {
      "metadata": {
        "id": "941nclxbzqGH",
        "colab_type": "code",
        "slideshow": {
          "slide_type": "-"
        },
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          },
          "test": {
            "output": "ignore",
            "timeout": 600
          }
        },
        "cellView": "both"
      },
      "source": [
        "calibration_data = pd.DataFrame()\n",
        "calibration_data[\"predictions\"] = pd.Series(predictions)\n",
        "calibration_data[\"targets\"] = pd.Series(targets)\n",
        "calibration_data.describe()"
      ],
      "cell_type": "code",
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "E2-bf8Hq36y8",
        "colab_type": "text",
        "slideshow": {
          "slide_type": "-"
        }
      },
      "cell_type": "markdown",
      "source": [
        " \u597d\u7684\uff0c\u6b64\u4fe1\u606f\u4e5f\u8bb8\u6709\u5e2e\u52a9\u3002\u5e73\u5747\u503c\u4e0e\u6a21\u578b\u7684 RMSE \u76f8\u6bd4\u60c5\u51b5\u5982\u4f55\uff1f\u5404\u79cd\u5206\u4f4d\u6570\u5462\uff1f\n",
        "\n",
        "\u6211\u4eec\u8fd8\u53ef\u4ee5\u5c06\u6570\u636e\u548c\u5b66\u5230\u7684\u7ebf\u53ef\u89c6\u5316\u3002\u6211\u4eec\u5df2\u7ecf\u77e5\u9053\uff0c\u5355\u4e2a\u7279\u5f81\u7684\u7ebf\u6027\u56de\u5f52\u53ef\u7ed8\u5236\u6210\u4e00\u6761\u5c06\u8f93\u5165 *x* \u6620\u5c04\u5230\u8f93\u51fa *y* \u7684\u7ebf\u3002\n",
        "\n",
        "\u9996\u5148\uff0c\u6211\u4eec\u5c06\u83b7\u5f97\u5747\u5300\u5206\u5e03\u7684\u968f\u673a\u6570\u636e\u6837\u672c\uff0c\u4ee5\u4fbf\u7ed8\u5236\u53ef\u8fa8\u7684\u6563\u70b9\u56fe\u3002"
      ]
    },
    {
      "metadata": {
        "id": "SGRIi3mAU81H",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        }
      },
      "source": [
        "sample = california_housing_dataframe.sample(n=300)"
      ],
      "cell_type": "code",
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "N-JwuJBKU81J",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        " \u7136\u540e\uff0c\u6211\u4eec\u6839\u636e\u6a21\u578b\u7684\u504f\u5dee\u9879\u548c\u7279\u5f81\u6743\u91cd\u7ed8\u5236\u5b66\u5230\u7684\u7ebf\uff0c\u5e76\u7ed8\u5236\u6563\u70b9\u56fe\u3002\u8be5\u7ebf\u4f1a\u4ee5\u7ea2\u8272\u663e\u793a\u3002"
      ]
    },
    {
      "metadata": {
        "id": "7G12E76-339G",
        "colab_type": "code",
        "slideshow": {
          "slide_type": "-"
        },
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          },
          "test": {
            "output": "ignore",
            "timeout": 600
          }
        },
        "cellView": "both"
      },
      "source": [
        "# Get the min and max total_rooms values.\n",
        "x_0 = sample[\"total_rooms\"].min()\n",
        "x_1 = sample[\"total_rooms\"].max()\n",
        "\n",
        "# Retrieve the final weight and bias generated during training.\n",
        "weight = linear_regressor.get_variable_value('linear/linear_model/total_rooms/weights')[0]\n",
        "bias = linear_regressor.get_variable_value('linear/linear_model/bias_weights')\n",
        "\n",
        "# Get the predicted median_house_values for the min and max total_rooms values.\n",
        "y_0 = weight * x_0 + bias \n",
        "y_1 = weight * x_1 + bias\n",
        "\n",
        "# Plot our regression line from (x_0, y_0) to (x_1, y_1).\n",
        "plt.plot([x_0, x_1], [y_0, y_1], c='r')\n",
        "\n",
        "# Label the graph axes.\n",
        "plt.ylabel(\"median_house_value\")\n",
        "plt.xlabel(\"total_rooms\")\n",
        "\n",
        "# Plot a scatter plot from our data sample.\n",
        "plt.scatter(sample[\"total_rooms\"], sample[\"median_house_value\"])\n",
        "\n",
        "# Display graph.\n",
        "plt.show()"
      ],
      "cell_type": "code",
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "t0lRt4USU81L",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        " \u8fd9\u6761\u521d\u59cb\u7ebf\u770b\u8d77\u6765\u4e0e\u76ee\u6807\u76f8\u5dee\u5f88\u5927\u3002\u770b\u770b\u60a8\u80fd\u5426\u56de\u60f3\u8d77\u6458\u8981\u7edf\u8ba1\u4fe1\u606f\uff0c\u5e76\u770b\u5230\u5176\u4e2d\u8574\u542b\u7684\u76f8\u540c\u4fe1\u606f\u3002\n",
        "\n",
        "\u7efc\u4e0a\u6240\u8ff0\uff0c\u8fd9\u4e9b\u521d\u59cb\u5065\u5168\u6027\u68c0\u67e5\u63d0\u793a\u6211\u4eec\u4e5f\u8bb8\u53ef\u4ee5\u627e\u5230\u66f4\u597d\u7684\u7ebf\u3002"
      ]
    },
    {
      "metadata": {
        "id": "AZWF67uv0HTG",
        "colab_type": "text",
        "slideshow": {
          "slide_type": "slide"
        }
      },
      "cell_type": "markdown",
      "source": [
        " ## \u8c03\u6574\u6a21\u578b\u8d85\u53c2\u6570\n",
        "\u5bf9\u4e8e\u672c\u7ec3\u4e60\uff0c\u4e3a\u65b9\u4fbf\u8d77\u89c1\uff0c\u6211\u4eec\u5df2\u5c06\u4e0a\u8ff0\u6240\u6709\u4ee3\u7801\u653e\u5165\u4e00\u4e2a\u51fd\u6570\u4e2d\u3002\u60a8\u53ef\u4ee5\u4f7f\u7528\u4e0d\u540c\u7684\u53c2\u6570\u8c03\u7528\u8be5\u51fd\u6570\uff0c\u4ee5\u4e86\u89e3\u76f8\u5e94\u6548\u679c\u3002\n",
        "\n",
        "\u6211\u4eec\u4f1a\u5728 10 \u4e2a\u7b49\u5206\u7684\u65f6\u95f4\u6bb5\u5185\u4f7f\u7528\u6b64\u51fd\u6570\uff0c\u4ee5\u4fbf\u89c2\u5bdf\u6a21\u578b\u5728\u6bcf\u4e2a\u65f6\u95f4\u6bb5\u7684\u6539\u5584\u60c5\u51b5\u3002\n",
        "\n",
        "\u5bf9\u4e8e\u6bcf\u4e2a\u65f6\u95f4\u6bb5\uff0c\u6211\u4eec\u90fd\u4f1a\u8ba1\u7b97\u8bad\u7ec3\u635f\u5931\u5e76\u7ed8\u5236\u76f8\u5e94\u56fe\u8868\u3002\u8fd9\u53ef\u4ee5\u5e2e\u52a9\u60a8\u5224\u65ad\u6a21\u578b\u6536\u655b\u7684\u65f6\u95f4\uff0c\u6216\u8005\u6a21\u578b\u662f\u5426\u9700\u8981\u66f4\u591a\u8fed\u4ee3\u3002\n",
        "\n",
        "\u6b64\u5916\uff0c\u6211\u4eec\u8fd8\u4f1a\u7ed8\u5236\u6a21\u578b\u968f\u7740\u65f6\u95f4\u7684\u63a8\u79fb\u5b66\u4e60\u7684\u7279\u5f81\u6743\u91cd\u548c\u504f\u5dee\u9879\u503c\u7684\u66f2\u7ebf\u56fe\u3002\u60a8\u8fd8\u53ef\u4ee5\u901a\u8fc7\u8fd9\u79cd\u65b9\u5f0f\u67e5\u770b\u6a21\u578b\u7684\u6536\u655b\u6548\u679c\u3002"
      ]
    },
    {
      "metadata": {
        "id": "wgSMeD5UU81N",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        }
      },
      "source": [
        "def train_model(learning_rate, steps, batch_size, input_feature=\"total_rooms\"):\n",
        "  \"\"\"Trains a linear regression model of one feature.\n",
        "  \n",
        "  Args:\n",
        "    learning_rate: A `float`, the learning rate.\n",
        "    steps: A non-zero `int`, the total number of training steps. A training step\n",
        "      consists of a forward and backward pass using a single batch.\n",
        "    batch_size: A non-zero `int`, the batch size.\n",
        "    input_feature: A `string` specifying a column from `california_housing_dataframe`\n",
        "      to use as input feature.\n",
        "  \"\"\"\n",
        "  \n",
        "  periods = 10\n",
        "  steps_per_period = steps / periods\n",
        "\n",
        "  my_feature = input_feature\n",
        "  my_feature_data = california_housing_dataframe[[my_feature]]\n",
        "  my_label = \"median_house_value\"\n",
        "  targets = california_housing_dataframe[my_label]\n",
        "\n",
        "  # Create feature columns.\n",
        "  feature_columns = [tf.feature_column.numeric_column(my_feature)]\n",
        "  \n",
        "  # Create input functions.\n",
        "  training_input_fn = lambda:my_input_fn(my_feature_data, targets, batch_size=batch_size)\n",
        "  prediction_input_fn = lambda: my_input_fn(my_feature_data, targets, num_epochs=1, shuffle=False)\n",
        "  \n",
        "  # Create a linear regressor object.\n",
        "  my_optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)\n",
        "  my_optimizer = tf.contrib.estimator.clip_gradients_by_norm(my_optimizer, 5.0)\n",
        "  linear_regressor = tf.estimator.LinearRegressor(\n",
        "      feature_columns=feature_columns,\n",
        "      optimizer=my_optimizer\n",
        "  )\n",
        "\n",
        "  # Set up to plot the state of our model's line each period.\n",
        "  plt.figure(figsize=(15, 6))\n",
        "  plt.subplot(1, 2, 1)\n",
        "  plt.title(\"Learned Line by Period\")\n",
        "  plt.ylabel(my_label)\n",
        "  plt.xlabel(my_feature)\n",
        "  sample = california_housing_dataframe.sample(n=300)\n",
        "  plt.scatter(sample[my_feature], sample[my_label])\n",
        "  colors = [cm.coolwarm(x) for x in np.linspace(-1, 1, periods)]\n",
        "\n",
        "  # Train the model, but do so inside a loop so that we can periodically assess\n",
        "  # loss metrics.\n",
        "  print(\"Training model...\")\n",
        "  print(\"RMSE (on training data):\")\n",
        "  root_mean_squared_errors = []\n",
        "  for period in range (0, periods):\n",
        "    # Train the model, starting from the prior state.\n",
        "    linear_regressor.train(\n",
        "        input_fn=training_input_fn,\n",
        "        steps=steps_per_period\n",
        "    )\n",
        "    # Take a break and compute predictions.\n",
        "    predictions = linear_regressor.predict(input_fn=prediction_input_fn)\n",
        "    predictions = np.array([item['predictions'][0] for item in predictions])\n",
        "    \n",
        "    # Compute loss.\n",
        "    root_mean_squared_error = math.sqrt(\n",
        "        metrics.mean_squared_error(predictions, targets))\n",
        "    # Occasionally print the current loss.\n",
        "    print(\"  period %02d : %0.2f\" % (period, root_mean_squared_error))\n",
        "    # Add the loss metrics from this period to our list.\n",
        "    root_mean_squared_errors.append(root_mean_squared_error)\n",
        "    # Finally, track the weights and biases over time.\n",
        "    # Apply some math to ensure that the data and line are plotted neatly.\n",
        "    y_extents = np.array([0, sample[my_label].max()])\n",
        "    \n",
        "    weight = linear_regressor.get_variable_value('linear/linear_model/%s/weights' % input_feature)[0]\n",
        "    bias = linear_regressor.get_variable_value('linear/linear_model/bias_weights')\n",
        "\n",
        "    x_extents = (y_extents - bias) / weight\n",
        "    x_extents = np.maximum(np.minimum(x_extents,\n",
        "                                      sample[my_feature].max()),\n",
        "                           sample[my_feature].min())\n",
        "    y_extents = weight * x_extents + bias\n",
        "    plt.plot(x_extents, y_extents, color=colors[period]) \n",
        "  print(\"Model training finished.\")\n",
        "\n",
        "  # Output a graph of loss metrics over periods.\n",
        "  plt.subplot(1, 2, 2)\n",
        "  plt.ylabel('RMSE')\n",
        "  plt.xlabel('Periods')\n",
        "  plt.title(\"Root Mean Squared Error vs. Periods\")\n",
        "  plt.tight_layout()\n",
        "  plt.plot(root_mean_squared_errors)\n",
        "\n",
        "  # Output a table with calibration data.\n",
        "  calibration_data = pd.DataFrame()\n",
        "  calibration_data[\"predictions\"] = pd.Series(predictions)\n",
        "  calibration_data[\"targets\"] = pd.Series(targets)\n",
        "  display.display(calibration_data.describe())\n",
        "\n",
        "  print(\"Final RMSE (on training data): %0.2f\" % root_mean_squared_error)"
      ],
      "cell_type": "code",
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "kg8A4ArBU81Q",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        " ## \u4efb\u52a1 1\uff1a\u4f7f RMSE \u4e0d\u8d85\u8fc7 180\n",
        "\n",
        "\u8c03\u6574\u6a21\u578b\u8d85\u53c2\u6570\uff0c\u4ee5\u964d\u4f4e\u635f\u5931\u548c\u66f4\u7b26\u5408\u76ee\u6807\u5206\u5e03\u3002\n",
        "\u7ea6 5 \u5206\u949f\u540e\uff0c\u5982\u679c\u60a8\u65e0\u6cd5\u8ba9 RMSE \u4f4e\u4e8e 180\uff0c\u8bf7\u67e5\u770b\u89e3\u51b3\u65b9\u6848\uff0c\u4e86\u89e3\u53ef\u80fd\u7684\u7ec4\u5408\u3002"
      ]
    },
    {
      "metadata": {
        "id": "UzoZUSdLIolF",
        "colab_type": "code",
        "slideshow": {
          "slide_type": "slide"
        },
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          },
          "test": {
            "output": "ignore",
            "timeout": 600
          }
        },
        "cellView": "both"
      },
      "source": [
        "train_model(\n",
        "    learning_rate=0.00001,\n",
        "    steps=100,\n",
        "    batch_size=1\n",
        ")"
      ],
      "cell_type": "code",
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "ajVM7rkoYXeL",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        " ### \u89e3\u51b3\u65b9\u6848\n",
        "\n",
        "\u70b9\u51fb\u4e0b\u65b9\u5373\u53ef\u67e5\u770b\u4e00\u79cd\u53ef\u80fd\u7684\u89e3\u51b3\u65b9\u6848\u3002"
      ]
    },
    {
      "metadata": {
        "id": "T3zmldDwYy5c",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        }
      },
      "source": [
        "train_model(\n",
        "    learning_rate=0.00002,\n",
        "    steps=500,\n",
        "    batch_size=5\n",
        ")"
      ],
      "cell_type": "code",
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "M8H0_D4vYa49",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        " \u8fd9\u53ea\u662f\u4e00\u79cd\u53ef\u80fd\u7684\u914d\u7f6e\uff1b\u4e5f\u8bb8\u8fd8\u6709\u540c\u6837\u80fd\u591f\u63d0\u4f9b\u7406\u60f3\u7ed3\u679c\u7684\u5176\u4ed6\u8bbe\u7f6e\u7ec4\u5408\u3002\u8bf7\u6ce8\u610f\uff0c\u603b\u4f53\u800c\u8a00\uff0c\u672c\u7ec3\u4e60\u91cd\u70b9\u4e0d\u662f\u67e5\u627e*\u4e00\u79cd\u6700\u4f73*\u8bbe\u7f6e\uff0c\u800c\u662f\u5e2e\u52a9\u60a8\u5bf9\u6a21\u578b\u914d\u7f6e\u8c03\u6574\u5982\u4f55\u5f71\u54cd\u9884\u6d4b\u8d28\u91cf\u6709\u4e00\u4e2a\u76f4\u89c2\u7684\u8ba4\u8bc6\u3002"
      ]
    },
    {
      "metadata": {
        "id": "QU5sLyYTqzqL",
        "colab_type": "text",
        "slideshow": {
          "slide_type": "slide"
        }
      },
      "cell_type": "markdown",
      "source": [
        " ### \u6709\u9002\u7528\u4e8e\u6a21\u578b\u8c03\u6574\u7684\u6807\u51c6\u542f\u53d1\u6cd5\u5417\uff1f\n",
        "\n",
        "\u8fd9\u662f\u4e00\u4e2a\u5e38\u89c1\u7684\u95ee\u9898\u3002\u7b80\u77ed\u7684\u7b54\u6848\u662f\uff0c\u4e0d\u540c\u8d85\u53c2\u6570\u7684\u6548\u679c\u53d6\u51b3\u4e8e\u6570\u636e\u3002\u56e0\u6b64\uff0c\u4e0d\u5b58\u5728\u5fc5\u987b\u9075\u5faa\u7684\u89c4\u5219\uff0c\u60a8\u9700\u8981\u5bf9\u81ea\u5df1\u7684\u6570\u636e\u8fdb\u884c\u6d4b\u8bd5\u3002\n",
        "\n",
        "\u5373\u4fbf\u5982\u6b64\uff0c\u6211\u4eec\u4ecd\u5728\u4e0b\u9762\u5217\u51fa\u4e86\u51e0\u6761\u53ef\u4e3a\u60a8\u63d0\u4f9b\u6307\u5bfc\u7684\u7ecf\u9a8c\u6cd5\u5219\uff1a\n",
        "\n",
        " * \u8bad\u7ec3\u8bef\u5dee\u5e94\u8be5\u7a33\u6b65\u51cf\u5c0f\uff0c\u521a\u5f00\u59cb\u662f\u6025\u5267\u51cf\u5c0f\uff0c\u6700\u7ec8\u5e94\u968f\u7740\u8bad\u7ec3\u6536\u655b\u8fbe\u5230\u5e73\u7a33\u72b6\u6001\u3002\n",
        " * \u5982\u679c\u8bad\u7ec3\u5c1a\u672a\u6536\u655b\uff0c\u5c1d\u8bd5\u8fd0\u884c\u66f4\u957f\u7684\u65f6\u95f4\u3002\n",
        " * \u5982\u679c\u8bad\u7ec3\u8bef\u5dee\u51cf\u5c0f\u901f\u5ea6\u8fc7\u6162\uff0c\u5219\u63d0\u9ad8\u5b66\u4e60\u901f\u7387\u4e5f\u8bb8\u6709\u52a9\u4e8e\u52a0\u5feb\u5176\u51cf\u5c0f\u901f\u5ea6\u3002\n",
        "   * \u4f46\u6709\u65f6\u5982\u679c\u5b66\u4e60\u901f\u7387\u8fc7\u9ad8\uff0c\u8bad\u7ec3\u8bef\u5dee\u7684\u51cf\u5c0f\u901f\u5ea6\u53cd\u800c\u4f1a\u53d8\u6162\u3002\n",
        " * \u5982\u679c\u8bad\u7ec3\u8bef\u5dee\u53d8\u5316\u5f88\u5927\uff0c\u5c1d\u8bd5\u964d\u4f4e\u5b66\u4e60\u901f\u7387\u3002\n",
        "   * \u8f83\u4f4e\u7684\u5b66\u4e60\u901f\u7387\u548c\u8f83\u5927\u7684\u6b65\u6570/\u8f83\u5927\u7684\u6279\u91cf\u5927\u5c0f\u901a\u5e38\u662f\u4e0d\u9519\u7684\u7ec4\u5408\u3002\n",
        " * \u6279\u91cf\u5927\u5c0f\u8fc7\u5c0f\u4e5f\u4f1a\u5bfc\u81f4\u4e0d\u7a33\u5b9a\u60c5\u51b5\u3002\u4e0d\u59a8\u5148\u5c1d\u8bd5 100 \u6216 1000 \u7b49\u8f83\u5927\u7684\u503c\uff0c\u7136\u540e\u9010\u6e10\u51cf\u5c0f\u503c\u7684\u5927\u5c0f\uff0c\u76f4\u5230\u51fa\u73b0\u6027\u80fd\u964d\u4f4e\u7684\u60c5\u51b5\u3002\n",
        "\n",
        "\u91cd\u7533\u4e00\u4e0b\uff0c\u5207\u52ff\u4e25\u683c\u9075\u5faa\u8fd9\u4e9b\u7ecf\u9a8c\u6cd5\u5219\uff0c\u56e0\u4e3a\u6548\u679c\u53d6\u51b3\u4e8e\u6570\u636e\u3002\u8bf7\u59cb\u7ec8\u8fdb\u884c\u8bd5\u9a8c\u548c\u9a8c\u8bc1\u3002"
      ]
    },
    {
      "metadata": {
        "id": "GpV-uF_cBCBU",
        "colab_type": "text",
        "slideshow": {
          "slide_type": "slide"
        }
      },
      "cell_type": "markdown",
      "source": [
        " ## \u4efb\u52a1 2\uff1a\u5c1d\u8bd5\u5176\u4ed6\u7279\u5f81\n",
        "\n",
        "\u4f7f\u7528 `population` \u7279\u5f81\u66ff\u6362 `total_rooms` \u7279\u5f81\uff0c\u770b\u770b\u80fd\u5426\u53d6\u5f97\u66f4\u597d\u7684\u6548\u679c\u3002\n",
        "\n",
        "\u8fd9\u90e8\u5206\u4e0d\u5fc5\u8d85\u8fc7 5 \u5206\u949f\u3002"
      ]
    },
    {
      "metadata": {
        "id": "YMyOxzb0ZlAH",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        }
      },
      "source": [
        "# YOUR CODE HERE"
      ],
      "cell_type": "code",
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "ci1ISxxrZ7v0",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        " ### \u89e3\u51b3\u65b9\u6848\n",
        "\n",
        "\u70b9\u51fb\u4e0b\u65b9\u5373\u53ef\u67e5\u770b\u4e00\u79cd\u53ef\u80fd\u7684\u89e3\u51b3\u65b9\u6848\u3002"
      ]
    },
    {
      "metadata": {
        "id": "SjdQQCduZ7BV",
        "colab_type": "code",
        "colab": {
          "autoexec": {
            "startup": false,
            "wait_interval": 0
          }
        }
      },
      "source": [
        "train_model(\n",
        "    learning_rate=0.00002,\n",
        "    steps=1000,\n",
        "    batch_size=5,\n",
        "    input_feature=\"population\"\n",
        ")"
      ],
      "cell_type": "code",
      "execution_count": 0,
      "outputs": []
    }
  ]
}
